package com.youku.expression.environment;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class GlobalEnvironment extends BaseEnvironment {

	private Map<String, Environment> localEnv = new LinkedHashMap<>();

	public void putEnvironment(String id, Environment environment) {
		localEnv.put(id, environment);
	}

	public Environment getEnvironment(String id) {
		Environment local=localEnv.get(id);
		if(local==null){
			local=new LocalEnvironment(this);
			localEnv.put(id, local);
		}
		return local;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("全局变量").append(super.toString());

		for (Entry<String, Environment> entry : localEnv.entrySet()) {
			String key = entry.getKey();
			Environment environment = entry.getValue();
			builder.append('\n').append("局部变量").append(key).append(environment.toString());
		}

		return builder.toString();
	}

	@Override
	public void clearInner() {
		localEnv.clear();
	}

}
